package com.biubiushop.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * Http工具类 Created by chenjia on 2019-06-04
 *
 */
public class HttpUtil {

	public static final String XML_ACCEPT = "application/xml";
	public static final String JSON_ACCEPT = "application/json";

	public static String buildGetUrl(String url, List<String> list) throws Exception {
		String[] params = list.toArray(new String[list.size()]);
		StringBuffer sb = new StringBuffer(url);
		// 将url对应的参数递归注入
		int i = 0;
		String str = recursiveInjection(sb, params, i).toString();
		return str;
	}

	private static StringBuffer recursiveInjection(StringBuffer sb, String[] params, int i) throws Exception {
		int offset = sb.indexOf("=?");
		if (offset != -1) {
			if (i > params.length - 1) {
				throw new Exception("缺少参数");
			}
			sb.replace(offset + 1, offset + 2, params[i]);
			i++;
			recursiveInjection(sb, params, i);
		}
		return sb;
	}

	public static String doGet(String url) throws Exception {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		HttpGet httpGet = new HttpGet(url);

		httpGet.addHeader("Content-type", "application/json; charset=utf-8");
		httpGet.setHeader("Accept", "application/json");

		HttpResponse response = httpclient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");
			return result;
		}
		return null;
	}

	public static String doPost(String url, String jsonString, String accept) throws Exception {
		CloseableHttpClient httpclient = HttpClientBuilder.create().build();
		HttpPost httpPost = new HttpPost(url);

		httpPost.addHeader("Content-type", accept + "; charset=utf-8");
		httpPost.setHeader("Accept", accept);
		httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));

		HttpResponse response = httpclient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			String result = EntityUtils.toString(entity, "UTF-8");
			return result;
		}
		return null;
	}

	public static void main(String[] args) {
		String url = "http://47.103.0.161:5003/shareTissue/test?id=89860441191840512520&length=10";
		String result = null;
		try {
			result = doGet(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(result);
	}

	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("Content-Type", "application/xml");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				// String line;
				result = result + line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 以下是百度身份证图片识别相关请求方法
	 */
	public static String post(String requestUrl, String accessToken, String params) throws Exception {
		String contentType = "application/x-www-form-urlencoded";
		return HttpUtil.post(requestUrl, accessToken, contentType, params);
	}

	public static String post(String requestUrl, String accessToken, String contentType, String params)
			throws Exception {
		String encoding = "UTF-8";
		if (requestUrl.contains("nlp")) {
			encoding = "GBK";
		}
		return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
	}

	public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
			throws Exception {
		String url = requestUrl + "?access_token=" + accessToken;
		return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
	}

	public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
			throws Exception {
		URL url = new URL(generalUrl);
		// 打开和URL之间的连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		// 设置通用的请求属性
		connection.setRequestProperty("Content-Type", contentType);
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);

		// 得到请求的输出流对象
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		out.write(params.getBytes(encoding));
		out.flush();
		out.close();

		// 建立实际的连接
		connection.connect();
		// 获取所有响应头字段
		Map<String, List<String>> headers = connection.getHeaderFields();
		// 遍历所有的响应头字段
		for (String key : headers.keySet()) {
			System.err.println(key + "--->" + headers.get(key));
		}
		// 定义 BufferedReader输入流来读取URL的响应
		BufferedReader in = null;
		in = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		System.err.println("result:" + result);
		return result;
	}
}
